package dl.demo.controller;

import dl.demo.entity.Project;
import dl.demo.repository.ProjectRepo;
import dl.demo.tool.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/project")
public class ProjectCtrl {
    @Autowired
    ProjectRepo projectRepo;

    @PostMapping
    ResponseEntity create(@Param("token")String token, @RequestBody Project project){
        if(JwtUtils.verifyToken(token) != 0)return Result.status(401);
        project.setUser_id((Integer) JwtUtils.parseToken(token).get("id"));
        projectRepo.save(project);
        return Result.data(project);
    }

    @GetMapping
    ResponseEntity get(@Param("token")String token,@Param("id")Integer id){
        Project project = projectRepo.findById(id).orElse(new Project());

        if(!project.isIspublic()){
            if(JwtUtils.verifyToken(token) == 0
                    && (JwtUtils.parseToken(token).get("id") == project.getUser_id())){
                return Result.data(project);
            }
            return Result.data(201,"项目不存在");
        }
        return Result.data(project);
    }
}
